/*
 *
 * Project Name: tennis
 * $Id:  PlayServiceImpl.java 2016-05-13 14:35:01 $
 */
package org.aceor.tennis.service.impl;

import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
import org.aceor.tennis.common.domain.Play;
import org.aceor.tennis.common.enums.ErrorCode;
import org.aceor.tennis.common.enums.PlayStatus;
import org.aceor.tennis.common.exception.BusinessRuntimeException;
import org.aceor.tennis.common.exception.CommonRuntimeException;
import org.aceor.tennis.dao.IBaseDAO;
import org.aceor.tennis.dao.IPlayDAO;
import org.aceor.tennis.service.IPlayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service("PlayServiceImpl")
public class PlayServiceImpl extends AbstractBaseService<IBaseDAO<Play>, Play> implements IPlayService<Play> {
    @Autowired
    private IPlayDAO playDAO;

    public IBaseDAO<Play> getDao() {
        return playDAO;
    }

    @Override
    public List<Play> queryUnderwayPlays(Integer offset, Integer rows) throws BusinessRuntimeException {
        try {
            return queryListByPage(ImmutableMap.of("status", PlayStatus.UNDERWAY.getValue()), offset, rows);
        } catch (Throwable t) {
            throw new BusinessRuntimeException("查询部分进行中的球局失败", t);
        }
    }

    @Override
    public List<Play> queryAllUnderwayPlays() throws BusinessRuntimeException {
        try {
            return findList("status", PlayStatus.UNDERWAY.getValue());
        } catch (Throwable t) {
            throw new BusinessRuntimeException("查询所有进行中的球局失败", t);
        }
    }

    @Override
    public List<Play> queryAllSelfCreatePlays(Long userId) throws BusinessRuntimeException {
        try {
            return queryList(ImmutableMap.of("createId", userId));
        } catch (Throwable t) {
            throw new BusinessRuntimeException("查询自己创建的球局失败", t);
        }
    }

    @Override
    public void cancelOnePlay(Long playId) throws BusinessRuntimeException {
        try {
            Optional<Play> playOptional = findOneById(playId);
            if (playOptional.isPresent()) {
                if (1 != update(playOptional.get())) {
                    throw new BusinessRuntimeException("取消球局失败");
                }
            } else {
                throw new BusinessRuntimeException(ErrorCode.PARAM_ERROR, "没有找到对应的球局");
            }
        } catch (CommonRuntimeException e) {
            throw e;
        } catch (Throwable t) {
            throw new BusinessRuntimeException("取消球局失败");
        }
    }

    @Override
    public Optional<Play> findOneById(Long id) throws BusinessRuntimeException {
        return Optional.of(fetch(id));
    }
}
